﻿using ZFY.Blog.Api.IRepository;
using ZFY.Blog.Api.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ZFY.Blog.Api.Fitler
{
    public class ResultFilter:ActionFilterAttribute
    {

        public ResultFilter()
        {
        }
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            
            base.OnResultExecuted(context);
        }
        public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.ModelState.IsValid)
            {
                object value = null;
                var resultList = new List<string> { "EmptyResult", "SignOutResult", "RedirectResult","FileReulst" };
                if (!resultList.Contains(context.Result.GetType().Name))
                {
                    value = (context.Result as dynamic)?.Value;
                    context.Result = new JsonResult(new ReponseModel { success = true, data = value, msg = "" });
                    context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
                }
                base.OnResultExecuting(context);
            }
            else
            {
                var list = new List<string>();
                foreach (var item in context.ModelState.Values)
                {
                    foreach (var error in item.Errors)
                    {
                        list.Add(error.ErrorMessage);
                    }
                }
                context.Result = new JsonResult(new ReponseModel { success = false, data = list, msg = "参数错误" });
                context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
            }
            await base.OnResultExecutionAsync(context, next);
        }
        //public override void OnResultExecuting(ResultExecutingContext context)
        //{

        //}
        public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            return base.OnActionExecutionAsync(context, next);
        }
    }
}
